package controller

import (
	"errors"
	"fmt"
	"github.com/e421083458/gorm"
	"github.com/gin-gonic/gin"
	"github.com/gogf/gf/util/gconv"
	"rock/customer/dto"
	"rock/customer/initParam"
	"rock/customer/middleware"
	"rock/customer/modules/redisModules"
	"strings"
)

// @Summary 检查用户
// @Description 传参只需要传UnionId。通过unionid 查询用户，如果用户不存在则新增一条记录
// @Tags 用户
// @ID /checkuser
// @Accept json
// @Produce json
// @Param polygon body dto.User true "body"
// @Success 200 {object} middleware.Response{data=dto.UserDetail} "success"
// @Router /checkuser [post]
func (w *WkbUserController) checkUser(router *gin.Context) {
	params := &dto.User{}
	if err := params.BindingParams(router); err != nil {
		middleware.ResponseError(router, middleware.PARMAS_ERROR_CODE, err)
		return
	}
	if params.UnionId == "" {
		middleware.ResponseError(router, middleware.PARMAS_ERROR_CODE, errors.New("unionId is not exist"))
		return
	}
	// 查询用户信息是否存在
	user, err := userService.UserByUnionId(router, InstanceDB, params.UnionId)
	if err != nil {
		if err.Error() != initParam.DataIsNotExist {
			middleware.ResponseError(router, middleware.INTERNAL_ERROR_CODE, err)
			return
		}
		middleware.ResponseError(router, middleware.USER_NOT_EXIST, err)
		return
	}
	// 缓存用户从哪个渠道进入
	redisModules.RedisChannelTypeUserId("ChannelType_"+gconv.String(user.UserId), params.ChannelType)
	// 从不同client进来，0 客服端；1 客户端
	if params.IsCustomerClient == 1 {
		user.UserIdRC = initParam.CTarget + gconv.String(user.UserId)
		if !strings.Contains(user.Avatar, "http") {
			user.Avatar = initParam.CAvatar
		}
		user.ImUserType = 1
	} else {
		// 查询客服信息
		csUser, err := customerServiceService.CsUserByUnionId(router, InstanceDB, params.UnionId)
		if err != nil {
			if err.Error() != initParam.DataIsNotExist {
				middleware.ResponseError(router, middleware.INTERNAL_ERROR_CODE, err)
				return
			}
			// 客户基本数据 赋给 客服
			csUser = user
		}
		// 获取客服小程序模式，0 审核模式，1 正式模式
		configMsg, err := serviceService.Config(router, BusinessDB, "isOpenAuthorization")
		if err != nil {
			if err.Error() != initParam.DataIsNotExist {
				middleware.ResponseError(router, middleware.INTERNAL_ERROR_CODE, err)
				return
			}
			middleware.ResponseError(router, middleware.DATA_NOT_EXIST, err)
			return
		}
		csUser.IsOpenAuthorization = gconv.Int(configMsg.Value)
		// 如果是删除状态，或者无状态，ImUserType 都为 1
		if csUser.Deleted < 2 {
			csUser.ImUserType = 1
			// 查询是否提交过注册信息
			if csUser.IsOpenAuthorization == 0 {
				csUser.IsRegister = 1
				_, err := customerServiceService.CsUserRegister(router, BusinessDB, csUser.Mobile)
				if err != nil {
					if err.Error() != initParam.DataIsNotExist {
						middleware.ResponseError(router, middleware.INTERNAL_ERROR_CODE, err)
						return
					}
					csUser.IsRegister = 0
				}
			}
			responseData := user
			middleware.ResponseSuccess(router, responseData)
			return
		}
		csUser.ImUserType = 2
		csUser.UserIdRC = initParam.CsTarget + gconv.String(csUser.UserId)
		csUser.Avatar = initParam.FAEAvatar
		// 查询是否有客服机器人群，没有则创建
		err = checkGroupRACs(router, gconv.String(csUser.UserId))
		if err != nil {
			if err.Error() != initParam.DataIsNotExist {
				middleware.ResponseError(router, middleware.INTERNAL_ERROR_CODE, err)
				return
			}
			middleware.ResponseError(router, middleware.DATA_NOT_EXIST, err)
			return
		}
		user = csUser
	}
	// 如果昵称为空，则 使用 realname
	if user.Nickname == "" {
		user.Nickname = user.RealName
	}
	// 更新融云用户信息
	rcParam := fmt.Sprintf("userId=%s&name=%s&portraitUri=%s", user.UserIdRC, user.Nickname, initParam.FAEAvatar)
	err = userRefreshRonCloud(user.UserIdRC, rcParam)
	if err != nil {
		middleware.ResponseError(router, middleware.INTERNAL_ERROR_CODE, err)
		return
	}
	responseData := user
	middleware.ResponseSuccess(router, responseData)
	return
}

// @Summary 客服注册手机号
// @Description
// @Tags 用户
// @ID /telregister
// @Accept json
// @Produce json
// @Param polygon body dto.UserInfo true "body"
// @Success 200 {object} middleware.Response{} "success"
// @Router /telregister [post]
func (w *WkbUserController) telRegister(router *gin.Context) {
	params := &dto.UserInfo{}
	if err := params.BindingParams(router); err != nil {
		middleware.ResponseError(router, middleware.PARMAS_ERROR_CODE, err)
		return
	}
	err := customerServiceService.CreateCsUserRegister(router, BusinessDB, gconv.Int(params.UserId), params.Mobile)
	if err != nil {
		middleware.ResponseError(router, middleware.INTERNAL_ERROR_CODE, err)
		return
	}
	middleware.ResponseSuccess(router, gin.H{"msg": initParam.DealSuccessText})
}

// @Summary 获取用户详情
// @Description 传参只需要传UserId
// @Tags 用户
// @ID /getuserdetail
// @Accept json
// @Produce json
// @Param polygon body dto.User true "body"
// @Success 200 {object} middleware.Response{data=dto.UserDetail} "success"
// @Router /getuserdetail [post]
func (w *WkbUserController) getUserDetail(router *gin.Context) {
	params := &dto.User{}
	if err := params.BindingParams(router); err != nil {
		middleware.ResponseError(router, middleware.PARMAS_ERROR_CODE, err)
		return
	}
	if strings.Contains(params.UserId, initParam.CTarget) {
		params.UserId = strings.Replace(params.UserId, initParam.CTarget, "", -1)
	}
	if strings.Contains(params.UserId, initParam.CsTarget) {
		params.UserId = strings.Replace(params.UserId, initParam.CsTarget, "", -1)
	}
	//
	data, err := userService.UserByUserId(router, InstanceDB, params.UserId)
	if err != nil {
		dealRequestError(router, err)
		return
	}
	data.Job = data.Autograph
	responseData := data
	middleware.ResponseSuccess(router, responseData)
}

// @Summary 后台客服修改信息
// @Description 传参只需要传UserId
// @Tags 用户
// @ID /updatecustomerservice
// @Accept json
// @Produce json
// @Param polygon body dto.User true "body"
// @Success 200 {object} middleware.Response{} "success"
// @Router /updatecustomerservice [post]
func (w *WkbUserController) updateCustomerService(router *gin.Context) {
	params := &dto.User{}
	if err := params.BindingParams(router); err != nil {
		middleware.ResponseError(router, middleware.PARMAS_ERROR_CODE, err)
		return
	}
	csUser, err := customerServiceService.CsUser(router, InstanceDB, gconv.Int(params.UserId))
	if err != nil {
		if !errors.Is(err, gorm.ErrRecordNotFound) {
			middleware.ResponseError(router, middleware.INTERNAL_ERROR_CODE, err)
			return
		}
	}
	//删除客服
	if csUser.UserId == 0 {
		//踢出客户群
		groupMemberList, err := groupService.GroupMemberList(router, BusinessDB, params.UserId)
		if err != nil {
			dealRequestError(router, err)
			return
		}
		for _, v := range groupMemberList {
			queryParam := dto.Group{
				GroupId:  v.GroupID,
				UserId:   params.UserId,
				QuitType: 3,
			}
			err = quitGroup(queryParam)
			if err != nil {
				middleware.ResponseError(router, middleware.INTERNAL_ERROR_CODE, err)
				return
			}
		}
		//解散客户群
		groupMemberAdminList, err := groupService.GroupMemberAdminList(router, BusinessDB, params.UserId)
		if err != nil {
			dealRequestError(router, err)
			return
		}
		for _, v := range groupMemberAdminList {
			queryParam := dto.Group{
				GroupId: v.GroupID,
				State:   3,
			}
			err = modifyGroupState(queryParam)
			if err != nil {
				middleware.ResponseError(router, middleware.INTERNAL_ERROR_CODE, err)
				return
			}
		}
	}

	middleware.ResponseSuccess(router, gin.H{"msg": initParam.DealSuccessText})
}
